<template>
  <el-form
    :model="formData"
    :label-width="labelWidth"
    ref="myForm"
    :validate-on-rule-change="false"
    :rules="props.rules"
    :label-position="labelPosition"
    :inline="props.inline"
  >
    <!-- 循环 -->
    <template v-for="(item, index) in props.columns" :key="index">
      <el-form-item
        v-if="item.formItem"
        :label="item.label + labelSymbol"
        :prop="item.prop"
      >
        <!-- 动态组件 -->
        <component
          :is="comObj?.[item.formItem?.type || 'input'] || WInput"
          v-model="formData[item.prop!]"
          v-bind="item.formItem?.[item.formItem?.type || 'input']"
        />
      </el-form-item>
    </template>
  </el-form>
</template>

<script lang="ts" setup>
import type { FormInstance } from "element-plus";
import { WSelect, WInput, WNumber, WSwitch } from "@/components/";
import { FormType } from "./interface/";

interface Emit {
  (event: "onSuccess", n: boolean): void;
  (event: "onCancel"): void;
}

const emit = defineEmits<Emit>();
const props = withDefaults(defineProps<FormType.Props>(), { labelSymbol: ":" });
const myForm = ref<FormInstance>();
const formData = reactive({ ...props.data });
console.log(43, { props, formData });
// 定义组件
const comObj: KeyStringAny<any> = {
  // text: WInput,
  select: WSelect,
  switch: WSwitch,
  number: WNumber,
  // color: WColor,
};

// 提交
const onSubmit = () => {
  // console.log(67, formData);
  return new Promise<FormType.Callback<any>>((resolve, reject) => {
    if (!myForm.value) {
      reject({ is: false, v: formData });
      return;
    }
    myForm.value?.validate(async (valid) => {
      if (valid) {
        resolve({ is: true, v: formData });
      } else {
        resolve({ is: false, v: formData });
      }
    });
  });
};
// 重置
const onReset = () => {
  if (!myForm.value) return;
  myForm.value.resetFields();
};

defineExpose({
  onSubmit,
  onReset,
});
</script>

<style lang="less" scoped>
@import url("./index.less");
</style>
